package com.atguigu.gmall.payment.controller;

import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.cart.pojo.UserInfo;
import com.atguigu.gmall.common.exception.OrderException;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.payment.config.AlipayTemplate;
import com.atguigu.gmall.payment.entity.PaymentInfoEntity;
import com.atguigu.gmall.payment.intercepter.LoginIntercepter;
import com.atguigu.gmall.payment.mapper.PaymentMapper;
import com.atguigu.gmall.payment.service.PaymentService;
import com.atguigu.gmall.payment.vo.PayAsyncVo;
import com.atguigu.gmall.payment.vo.PayVo;
import com.atguigu.gmall.ums.entity.UserEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;

@Controller
public class PaymentController {
    @Autowired
    PaymentService paymentService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    PaymentMapper paymentMapper;
    @Autowired
    AlipayTemplate alipayTemplate;
    @GetMapping("pay.html")
    public String toPay(@RequestParam String orderToken, Model model){

        OrderEntity orderEntity =  paymentService.getOrderInfo(orderToken);
        checkOrderState(orderToken,orderEntity);
        model.addAttribute("orderEntity",orderEntity);
        return "pay";
    }


    @GetMapping("alipay.html")
    @ResponseBody
    public Object alipay(String orderToken){
        OrderEntity orderEntity =  paymentService.getOrderInfo(orderToken);
        checkOrderState(orderToken,orderEntity);
        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderToken);
        //商品回传的参数，记账上的对应的订单id
      PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
      int insert =  this.paymentService.initOrderState(orderToken,orderEntity,paymentInfoEntity);
        if (insert==0){
            throw new OrderException("系统异常，本次交易未计入账册");
        }
        payVo.setPassback_params(paymentInfoEntity.getId().toString());
        payVo.setSubject("谷粒商城商品");
//        payVo.setTotal_amount(orderEntity.getTotalAmount().toString());
        payVo.setTotal_amount("0.01");
        String result = null;
        try {
            result = alipayTemplate.pay(payVo);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;
    }

    //同步的回调
    @GetMapping("pay/success")
    public String success(PayAsyncVo vo,Model model){
    //查询订单详情显示在页面上
        if (vo!= null){
            OrderEntity orderInfo = this.paymentService.getOrderInfo(vo.getOut_trade_no());
            model.addAttribute("orderEntity",orderInfo);
        }

        return "paysuccess";
    }
    //异步的回调
    @PostMapping("pay/ok")
    @ResponseBody
    public String ok(PayAsyncVo vo){
        Boolean signature = alipayTemplate.checkSignature(vo);
        if (signature){
            String orderId = vo.getPassback_params();
            PaymentInfoEntity paymentInfoEntity = this.paymentMapper.selectById(orderId);
            //如果没有查询到对应id的账单记录，则直接返回失败
            if (paymentInfoEntity==null){
                return "failure";
            }
            //核对查询的结果
            String outTradeNo = paymentInfoEntity.getOutTradeNo();
//            BigDecimal totalAmount = paymentInfoEntity.getTotalAmount();
            BigDecimal totalAmount = new BigDecimal("0.01");
            if (!StringUtils.equals(outTradeNo,vo.getOut_trade_no())||
                    totalAmount.compareTo(new BigDecimal(vo.getTotal_amount()))!=0||
               !StringUtils.equals(this.alipayTemplate.getApp_id(),vo.getApp_id())){
                return  "failure";
            }
            //查看支付宝的交易状态
            String trade_status = vo.getTrade_status();
            if (!StringUtils.equals("TRADE_SUCCESS",trade_status)){
                return  "failure";
            }
            //以上都不是，支付正常，保存支付的账单信息
            this.paymentService.paySuccess(vo);
            //发送信息给wms和oms，更新订单状态，更新库存
            this.rabbitTemplate.convertAndSend("ORDER_PAY_EXCHANGE","pay.success",vo.getOut_trade_no());
            return "success";
        }else {
            return "failure";
        }
    }

    //确认订单状态的方法
    private void checkOrderState(String orderToken,OrderEntity orderEntity){
        //根据orderToken查询订单信息并返回给页面
        //对订单的信息进行验证
        //1.订单对象是否为空
        if (orderEntity==null){
            throw  new OrderException("参数异常！！");
        }
        //2.是否是自己的订单
        Long userId = orderEntity.getUserId();
        UserInfo userInfo = LoginIntercepter.getUserInfo();
        if (userId!=userInfo.getUserId()){
            throw new OrderException("不是您的订单，无法支付");
        }
        //3.订单状态是否异常
        if(orderEntity.getStatus()!=0){
            throw new OrderException("订单状态异常");
        }
    }
}
